import { message } from 'antd'
import BusinessError from '@/core/framework/error/BusinessError'
import UnauthorizedError from '@/core/framework/error/UnauthorizedError'
import ForbiddenError from '@/core/framework/error/ForbiddenError'
import authService from '@/core/auth/service/authService'

export class ControllerHelper<R> {
	private promise: Promise<any>

	constructor(promise: () => Promise<R>) {
		this.promise = promise()
	}

	then(fn: (r: R) => R): ControllerHelper<R> {
		this.promise = this.promise.then(fn)
		return this
	}

	catch(fn: (reason: any) => Promise<any>): ControllerHelper<R> {
		this.promise = this.promise.catch(fn)
		return this
	}

	finally(fn: () => void): ControllerHelper<R> {
		this.promise = this.promise.finally(fn)
		return this
	}

	ifFailurePopMessage(): ControllerHelper<R> {
		this.promise.catch((error: Error) => {
			console.log('ifFailurePopMessage')
			if (error instanceof BusinessError) {
				message.error(error.message)
				return
			}
			if (error instanceof UnauthorizedError) {
				message.error(error.message)
				return
			}
			if (error instanceof ForbiddenError) {
				message.error(error.message)
				return
			}
			message.error('服务异常,请稍候再试')
			return
		})
		return this
	}

	ifUnauthorizedFailureThenRedirectLogin(): ControllerHelper<R> {
		this.promise.catch(async (error: Error) => {
			console.log('ifUnauthorizedFailureThenRedirectLogin')
			if (error instanceof UnauthorizedError) {
				await authService.logout()
			}
		})
		return this
	}

	doWithDefault = (): Promise<R> => {
		this.ifFailurePopMessage().ifUnauthorizedFailureThenRedirectLogin().catchDefault()
		return this.do()
	}

	do = (): Promise<R> => {
		return this.promise
	}

	catchDefault = (): ControllerHelper<R> => {
		this.promise = this.promise.catch((error: Error) => {
			console.log('catchDefault')
		})
		return this
	}
	catchLog = (): ControllerHelper<R> => {
		this.promise = this.promise.catch((error: Error) => {
			console.error(error)
		})
		return this
	}
}
